﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NFinal.OAuth.Controllers
{
    public class WeiXinController : BaseController
    {
        [GetHtml("/OAuth/WeiXin/Index.html")]
        public void Index()
        {
            //获得配置信息
            OAuthConfig config = ConfigHelper.get_config(this.config, "weixin");
            if (config == null)
            {
                this.Write("出错了，您尚未配置微信的API信息！");
                return;
            }
            string state = Guid.NewGuid().ToString().Replace("-", "");
            Session["oauth_state"] = state;
            string send_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + config.oauth_app_id 
                + "&redirect_uri=" + Uri.EscapeUriString(NFinal.Config.Configration.globalConfig.server.url + this.Url("ReturnUrl")) + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
            //开始发送
            this.Redirect(send_url);
        }
        [GetHtml("/OAuth/WeiXin/ReturnUrl.html")]
        public void ReturnUrl()
        {
            //取得返回参数
            string state = this.parameters["state"];
            string code = this.parameters["code"];

            string access_token = string.Empty;
            string expires_in = string.Empty;
            string client_id = string.Empty;
            string openid = string.Empty;

            if (Session["oauth_state"] == null || Session["oauth_state"].ToString() == "" || state != Session["oauth_state"].ToString())
            {
                this.Write("出错啦，state未初始化！");
                return;
            }
            if (string.IsNullOrEmpty(code))
            {
                this.Write("出错啦，无法获取用户授权信息！");
                return;
            }
            //获得配置信息
            OAuthConfig config = ConfigHelper.get_config(this.config, "weixin");
            //第一步：获取Access Token
            Dictionary<string, object> dic = OAuth.WeiXinHelper.get_access_token(config, this.Url("ReturnUrl"), code);
            if (dic == null || !dic.ContainsKey("access_token"))
            {
                this.Write("出错了，无法获取Access Token，请检查App Key是否正确！");
                return;
            }
            access_token = dic["access_token"].ToString();
            expires_in = dic["expires_in"].ToString();
            openid = dic["openid"].ToString();
            //储存获取数据用到的信息
            Session["oauth_name"] = "weixin";
            Session["oauth_access_token"] = access_token;
            Session["oauth_openid"] = openid;

            //第二步：跳转到指定页面
            //Response.Write(access_token);
            this.Redirect(this.config.JsonObject["oauth"]["loginSuccessUrl"]);
        }
        [GetHtml("/OAuth/WeiXin/Info.html")]
        public void Info()
        {
            string oauth_access_token = string.Empty;
            string oauth_openid = string.Empty;
            string oauth_name = string.Empty;

            if (Session["oauth_name"] == null || Session["oauth_access_token"] == null || Session["oauth_openid"] == null)
            {
                this.Write("{\"ret\":\"1\", \"msg\":\"出错啦，Access Token已过期或不存在！\"}");
                return;
            }
            oauth_name = Session["oauth_name"].ToString();
            oauth_access_token = Session["oauth_access_token"].ToString();
            oauth_openid = Session["oauth_openid"].ToString();
            Dictionary<string, object> dic = OAuth.WeiXinHelper.get_info(oauth_access_token, oauth_openid);
            if (dic == null)
            {
                this.Write("{\"ret\":\"1\", \"msg\":\"出错啦，无法获取授权用户信息！\"}");
                return;
            }
            this.Write("{");
            this.Write("\"ret\": \"0\", ");
            this.Write("\"msg\": \"获得用户信息成功！\", ");
            this.Write("\"oauth_name\": \"" + oauth_name + "\", ");
            this.Write("\"oauth_access_token\": \"" + oauth_access_token + "\", ");
            this.Write("\"oauth_openid\": \"" + dic["user_id"].ToString() + "\", ");
            this.Write("\"nick\": \"" + dic["nickname"].ToString() + "\", ");
            this.Write("\"avatar\": \"" + dic["headimgurl"].ToString() + "\", ");
            if (dic["sex"].ToString() == "1")
            {
                this.Write("\"sex\": \"男\", ");
            }
            else if (dic["sex"].ToString() == "f")
            {
                this.Write("\"sex\": \"女\", ");
            }
            else
            {
                this.Write("\"sex\": \"保密\", ");
            }
            this.Write("\"birthday\": \"\"");
            this.Write("\"city\":\""+dic["city"].ToString()+"\",");
            this.Write("\"province\":\"" + dic["province"].ToString() + "\",");
            this.Write("\"country\":\"" + dic["country"].ToString() + "\",");
            this.Write("}");
        }
    }
}
